<?php

namespace app\admin\controller\shop\task;

use app\common\controller\Backend;
use think\Db;

/**
 * 任务管理
 *
 * @icon fa fa-circle-o
 */
class Task extends Backend
{

    /**
     * Task模型对象
     * @var \app\common\model\shop\Task
     */
    protected $model = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'task_id';


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\shop\Task;

    }

    /**http://shuadan.me/admin/shop/task/lists?ref=addtabs#con_1
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {

                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //
            $join[] = ['shop s', 's.shop_id = t.shop_id'];
            $join[] = ['admin a', 'a.id = t.shop_admin_id'];
            $join[] = ['shop_task_key k', 'k.task_id = t.task_id'];
            $field  = "t.task_id,t.goods_sno,t.task_sno,s.shop_name,t.create_time,t.service_change_price,t.task_status,t.send_time,s.shop_admin_id,t.task_type,t.total_task_num,t.left_task_num,s.gold_bean,t.beat_price,a.username";

            $total  = $this->model->alias('t')->join($join)->field($field)->where($where)->count();
            $list   = $this->model->alias('t')->join($join)->field($field)->where($where)->limit($offset, $limit)->select();

           // dump($this->model->getLastSql());die;
            foreach ($list as $key => $value) {
               $keyword = $value->task_key;
                foreach ($keyword as $k => $v) {
                    $arr[] .= $v->key_word;
                }
                if($value['task_status'] == 1){
                    $value['task_status'] == '未发布';
                }else{
                    if($value['left_task_num'] == 0){
                        $value['task_status'] = '已完成';
                    }else{
                        $value['task_status'] = '已发布';
                    }
                }

                $value['task_use_num'] = $value['total_task_num'] - $value['left_task_num'];
                $value['key_word'] = implode(',', $arr);
                unset($arr);
            }
            unset($value);

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
}
